#coding=utf-8
import urllib,urllib2, subprocess,socket,sys,datetime
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'gaeproxy.settings'
from gaeproxy.gaehost.models import App

url = 'http://%s.appspot.com/fetch.py'
url2 = 'http://%s.jayproxy.com/fetch.py'

proxy_program = '/home/jay/py/gappproxy/localproxy/proxy.py'
log_dir = '/home/jay/py/gaeproxy/log'

def is_gfwed(app_id):
  socket.setdefaulttimeout(5)
  try:
    urllib.urlopen(url%app_id)
  except IOError,e:
    errno, errstr = sys.exc_info()[:2]
    if str(errstr).find('timed out') !=-1:
      return True
    else:
      return False
  else:
    return False

def is_overquota(app_id):
  f = urllib.urlopen(url2%app_id)
  code = f.getcode()
  if code == 503:
    return True
  return False

def start_proxy(app_id, use_reverse_proxy=False):
  app = App.objects.get(app_id=app_id)
  
  if use_reverse_proxy:
    command = ['python', proxy_program, '-r', '-a', app.app_id, '-p', app.port]
    app.using_reverseproxy = True
  else:
    command = ['python', proxy_program, '-a', app.app_id, '-p', app.port]
    app.using_reverseproxy = False
    
  access_log = os.path.join(log_dir, '%s_acess.log'%app.app_id)
  err_log = os.path.join(log_dir, '%s_err.log'%app.app_id)
  
  p = subprocess.Popen(command, stderr=open(access_log, 'a'), stdout=open(err_log,'a'))
  
  app.pid = p.pid
  app.save()
  
def check_proxy_running(app_id):
  app = App.objects.get(app_id=app_id)
  if not app.pid:
    return False
  ps = subprocess.Popen(['ps', app.pid], stdout=subprocess.PIPE).communicate()[0]
  if ps.find(app_id) == -1:
    app.pid = None
    app.save()
    return False
  return True
    
def kill_proxy(app_id):
  app = App.objects.get(app_id=app_id)
  subprocess.Popen(['kill', app.pid])
  app.pid = None
  app.save()

def print_red(s):
  print '\033[0;31;48m%s\033[0m'%s  
  
if __name__ == '__main__':
  n = datetime.datetime.now()
  m = n.minute
  print n
  for app in App.objects.order_by('created_at'):
    app.is_gfwed = is_gfwed(app.app_id)
    app.is_overquota = is_overquota(app.app_id)
    app.save()
    print_red(app)
    print 'is_normal', app.is_normal
    print 'is_gfwed', app.is_gfwed
    print 'is_overquota', app.is_overquota
  
  for app in App.objects.order_by('created_at'):
    app_id = app.app_id
    print_red(app)
    
    if app.is_overquota:
      if check_proxy_running(app_id):kill_proxy(app_id)
      print 'overquta:%s'%app
      continue
      
    if app.is_gfwed:
      print 'gfwed:%s'%app
      if check_proxy_running(app_id):
        if not app.using_reverseproxy:
          kill_proxy(app_id)
          start_proxy(app_id, True)
      else:
          start_proxy(app_id, True)
      continue
    
    if app.is_normal:
      print 'normal:%s'%app
      if not check_proxy_running(app_id):
        start_proxy(app_id)
        continue
      if app.using_reverseproxy and m%30 == 0:
        kill_proxy(app_id)
        start_proxy(app_id)
        continue
  
